package 多线程.交替输出;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.LockSupport;


/**
 * @author : K k
 * @date : 10:04 2020/8/19
 * 交替输出数字
 * 细节 notify方法不会立刻释放锁 而是等待synchronized锁住的方法或代码块执行完才释放
 */
public class SwapOutputDemo {
    private static volatile int index=1; //要输出的数字
    private static final Object lock = new Object();  //表示对象锁
    public static volatile boolean flag = false;  //是否被线程T1打印过
    static Thread t1=null,t2=null;


    public static void main(String[] args) {
        t1=new Thread(()->{
           for (int i=0;i<50;i++){
                synchronized (lock){
                    if (flag){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("线程1："+index);
                    index++;
                    flag=true;
                    lock.notifyAll();
                }
           }
        });

        t2=new Thread(()->{
            for (int i=0;i<50;i++){
                synchronized (lock){
                    if (!flag){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("线程2："+index);
                    index++;
                    flag=false;
                    lock.notifyAll();
                }
            }
        });

        t1.start();
        t2.start();


    }
}
